<template>
  <div class="announcement-manage">
    <div class="header" v-if="userStore.user?.role !== 'USER'">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">新增公告</el-button>
    </div>
    <el-table :data="announcementStore.announcements" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
      <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            v-if="userStore.user?.role !== 'USER'"
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            v-if="userStore.user?.role !== 'USER'"
            type="danger"
            size="small"
            @click="announcementStore.deleteAnnouncement(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增公告对话框 -->
    <el-dialog title="新增公告" v-model="createDialogVisible" width="30%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="createForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="createForm.content" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createAnnouncement" :icon="Plus">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改公告对话框 -->
    <el-dialog title="修改公告" v-model="editDialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="editFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="editForm.content" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAnnouncement" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { useAnnouncementStore } from '@/stores/api/announcement';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const announcementStore = useAnnouncementStore();
const userStore = useUserStore();

const createDialogVisible = ref(false);
const editDialogVisible = ref(false);

const createForm = ref({
  title: '',
  content: '',
});

const editForm = ref({
  id: 0,
  title: '',
  content: '',
});

const formRules = ref<FormRules>({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
});

const createFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

const fetchAnnouncements = async () => {
  try {
    await announcementStore.fetchAnnouncements();
  } catch (error: any) {
    ElMessage.error('获取公告列表失败');
  }
};

const showCreateDialog = () => {
  createForm.value = { title: '', content: '' };
  createDialogVisible.value = true;
};

const createAnnouncement = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await announcementStore.createAnnouncement(createForm.value);
        createDialogVisible.value = false;
        fetchAnnouncements();
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const showEditDialog = (announcement: any) => {
  editForm.value = { ...announcement, id: announcement.id };
  editDialogVisible.value = true;
};

const updateAnnouncement = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await announcementStore.updateAnnouncement(editForm.value);
        editDialogVisible.value = false;
        fetchAnnouncements();
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

onMounted(() => {
  fetchAnnouncements();
});
</script>

<style scoped>
.announcement-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.el-button i + span {
  margin-left: 8px;
}
.el-select {
  width: 100%;
}
</style>